package com.cctc.mychat.common.protocol.codec;

import com.cctc.mychat.common.protocol.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.List;

public class MessageCodec extends MessageToMessageCodec<ByteBuf, Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message message, List<Object> list) throws Exception {
        ByteBuf byteBuf = ctx.channel().alloc().buffer();
        MessageCodecManager.encode(byteBuf, message);
        list.add(byteBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception {
        Message message = MessageCodecManager.decode(byteBuf);
        if (message != null) {
            list.add(message);
        }
    }
}
